<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品 </el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row>
        <el-alert
          title="添加商品信息"
          type="info"
          center
          show-icon
          :closable="false"
        ></el-alert>
      </el-row>
      <el-row>
        <el-steps
          :space="200"
          :active="activeindex - 0"
          finish-status="success"
          align-center
        >
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
      </el-row>
      <el-row>
        <el-form
          :model="saveobj"
          :rules="checkform"
          ref="ruleForm"
          class="demo-ruleForm"
          label-position="top"
        >
          <el-tabs
            tab-position="left"
            v-model="activeindex"
            :before-leave="changetab"
            @tab-click="clicktab()"
          >
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="saveobj.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input
                  v-model="saveobj.goods_price"
                  type="number"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input
                  v-model="saveobj.goods_weight"
                  type="number"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input
                  v-model="saveobj.goods_number"
                  type="number"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品分类">
                <el-cascader
                  v-model="selectkeys"
                  :options="typelist"
                  :props="{
                    expandTrigger: 'hover',
                    label: 'cat_name',
                    value: 'cat_id',
                  }"
                  @change="handleChange"
                ></el-cascader>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
              <el-form-item
                v-for="(item, index) in paramslist"
                :label="item.attr_name"
                :key="index"
              >
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox
                    v-for="(value, key) in item.attr_vals"
                    :label="value"
                    :key="key"
                    border
                    >{{ value }}</el-checkbox
                  >
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
              <el-form-item
                v-for="(item, index) in staticlist"
                :label="item.attr_name"
                :key="index"
              >
                <el-input v-model="item.attr_vals" type="text"></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
              <el-upload
                list-type="picture"
                :action="uploadApi"
                :headers="headersobj"
                :on-success="uploadSuccess"
                :on-remove="handleRemove"
              >
                <el-button size="small" type="primary">上传商品图片</el-button>
                <div slot="tip" class="el-upload__tip">
                  对文件要求的提示信息
                </div>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
              <quill-editor
                v-model="saveobj.goods_introduce"
                ref="myQuillEditor"
              >
              </quill-editor>
              <el-row class="btntop">
                <el-button type="primary" @click="save()">保存</el-button>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </el-row>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="isShowImg" width="60%">
      <div style="width: 80%; margin: 0 auto">
        <img style="width: 100%" :src="imgurl" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "goods_add",
  data() {
    return {
      activeindex: "0",
      typelist: [],
      selectkeys: [],
      saveobj: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        pics: [],
        goods_introduce: "",
        goods_cat: "",
        attrs: [],
      },
      checkform: {
        goods_name: [
          { require: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { require: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { require: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { require: true, message: "请输入商品数量", trigger: "blur" },
        ],
      },
      paramslist: [],
      staticlist: [],
      uploadApi: "http://127.0.0.1:8888/api/private/v1/upload",
      headersobj: { Authorization: window.sessionStorage.getItem("token") },
      isShowImg: false,
      imgurl: "",
    };
  },
  methods: {
    handleChange() {
      if (this.selectkeys.length != 3) {
        this.selectkeys = [];
        return;
      }
    },
    async querytype() {
      let rst = await this.$http.get("categories");
      if (rst.meta.status == 200) {
        this.typelist = rst.data;
        console.log(rst);
      } else {
        this.$message.error("获取商品分类列表");
      }
    },
    changetab(form, to) {
      if (this.selectkeys.length != 3) {
        this.$message.error("请选择第三级分类");
        return false;
      }
      return true;
    },
    async getparams() {
      let id = this.selectkeys[2];
      let rst = await this.$http.get(`categories/${id}/attributes`, {
        sel: "many",
      });
      console.log(rst);
      if (rst.meta.status == 200) {
        this.paramslist = rst.data;
        this.paramslist.forEach((item, i) => {
          if (item.attr_vals) {
            item.attr_vals =
              item.attr_vals.length === 0 ? [] : item.attr_vals.split("");
          }
        });
      } else {
        this.$message.error("参数列表获取失败");
      }
    },
    clicktab() {
      if (this.activeindex == 1) {
        this.getparams();
      } else if (this.activeindex == 2) {
        this.getstatic();
      }
    },
    async getstatic() {
      let id = this.selectkeys[2];
      let rst = await this.$http.get(`categories/${id}/attributes`, {
        sel: "only",
      });
      if (rst.meta.status == 200) {
        this.staticlist = rst.data;
      } else {
        this.$message.error("静态属性列表获取失败");
        return;
      }
    },
    uploadSuccess(rst) {
      const picinfo = { pic: rst.data.tmp_path };
      this.saveobj.pics.push(picinfo);
    },
    handleRemove(file) {
      let tmppath = file.response.data.tmp_path;
      let index = this.saveobj.pics.findIndex((item) => {
        return item.pic == tmppath;
      });
      this.saveobj.pics.splice(index, 1);
      console.log(this.saveobj.pics);
    },
    handlePreview(file) {
      this.imgurl = file.response.data.url;
      this.isShowImg = true;
    },

    save() {
      this.$refs.ruleForm.validate(async (valid) => {
        console.log(valid);
        if (valid) {
          this.saveobj.goods_cat = this.selectkeys.join(",");
          this.paramslist.forEach((item, index) => {
            let { attr_id, attr_vals } = item;
            this.saveobj.attrs.push({
              attr_id: attr_id,
              attr_value: attr_vals.join(' '),
            });
          });
          this.staticlist.forEach((item, index) => {
            let { attr_id, attr_vals } = item;
            this.saveobj.attrs.push({
              attr_id: attr_id,
              attr_value: attr_vals,
            });
          });
          console.log(this.saveobj);
          let rst = await this.$http.post("goods", this.saveobj);
          console.log(rst);
          if (rst.meta.status == 201) {
            this.$router.replace("/home/goods");
          } else {
            this.$message.error("添加商品失败");
          }
        } else {
          console.log("验证不通过");
          this.activeindex = "0";
          return false;
        }
      });
    },
  },
  mounted() {
    this.querytype();
  },
};
</script>

<style>
.el-steps {
  margin: 15px;
}
.el-step__title {
  font-size: 13px;
}
.el-checkbox {
  margin: 0 5px !important;
}
.ql-editor {
  min-height: 360px !important;
}
.btntop {
  margin-top: 20px;
}
</style>